#include <stdio.h>
#include <utmp.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

extern int utmp_open(char *);
extern void utmp_close();

void showtime(long);
void show_info(struct utmp *);

#define SHOWHOST

int main(){
	struct utmp * utbufp, *utmp_next();
	
	if (utmp_open(UTMP_FILE) == -1){
		perror(UTMP_FILE);
		exit(1);
	}

	//read a record from utmp buffer until all the records in buffer are taken
	//then utmp_next will call read() to get another dozen records from UTMP_FILE
	while ((utbufp = utmp_next()) != (struct utmp *)NULL){
		show_info(utbufp);
	}
	utmp_close();
	return 0;
}

//display components in utmp file
void show_info(struct utmp * utbufp){
	if (utbufp->ut_type != USER_PROCESS){
		return;
	}
	printf("%-8.12s", utbufp->ut_name);	//the logname
	printf(" ");
	printf("%-8.12s", utbufp->ut_line); //the tty
	printf(" ");
	showtime(utbufp->ut_time);
	#ifdef SHOWHOST
		if (utbufp->ut_host[0] != '\0')
			printf("(%s)", utbufp->ut_host); //the host
	#endif
		printf("\n");
}

//convert absolute time value to String format that 
//human can read
void showtime(time_t timeval){
	char * cp;
	cp = ctime(&timeval);
	printf("%12.12s", cp + 4);	//pick 12 char from position 4
}
